<template>
  <view :data-theme="globPrimary" class="order">
    <u-navbar title="确认订单"></u-navbar>
    <mescroll-body
      ref="mescrollRef"
      :height="mescrollHeight"
      @init="mescrollInit"
      @down="downCallback"
      @up="getOrderCourse"
    >
      <view class="order-wrap u-flex" v-if="!$u.test.empty(orderData)">
        <courseImage
          :width="260"
          :height="144"
          :image="orderData.cover_url"
          :courseType="orderData.course_type"
          :courseTypeText="orderData.course_type_text"
          :promotionType="orderData.promotion_type"
          :promotionTypeText="orderData.promotion_type_text"
        ></courseImage>
        <view class="content">
          <view class="title u-line-2">
            {{ orderData.title }}
          </view>
          <view class="u-flex u-row-right">
            <view class="count">{{ `${orderData.section_count}课时` }}</view>
          </view>
          <view class="u-flex u-row-between">
            <view class="price">
              <block v-if="userInfo.is_vip == 1">vip:</block>
              {{ usePrice | formatCurrency }}
            </view>
            <view class="count" v-if="orderData.term_time == 0">永久有效</view>
            <view class="count" v-if="orderData.term_time < 10000 && orderData.term_time != 0"
              >购买之日起<label style="color: #f54030">{{ orderData.term_time }}</label
              >天内有效</view
            >
            <view class="count" v-if="orderData.term_time >= 10000"
              >{{ orderData.term_time | handleTime }}前有效</view
            >
          </view>
        </view>
      </view>

      <!-- 活动等于空不显示卡卷 -->
      <template v-if="!$u.test.empty(orderData)">
        <u-cell-group
          :border="false"
          class="order-coupon"
          v-if="
            $u.test.empty(orderData.positive_promotion) ||
            orderData.positive_promotion.running_status == 0
          "
        >
          <u-cell-item
            title="卡券"
            :value="text"
            :border-bottom="false"
            hover-class="none"
            :value-style="{ color: isCoupon == 0 ? '' : '#FF8A52' }"
            @click="openCoupon"
          ></u-cell-item>
          <u-cell-item
            v-if="credit_arr.length != 0"
            title="积分"
            :value="text2"
            :border-bottom="false"
            hover-class="none"
            :value-style="{ color: isCredit == 0 ? '' : '#FF8A52' }"
            @click="openCoupon2"
          ></u-cell-item>
        </u-cell-group>
        <u-cell-group :border="false" class="order-coupon" v-else>
          <u-cell-item
            v-if="credit_arr.length != 0"
            title="积分"
            :value="text2"
            :border-bottom="false"
            hover-class="none"
            :value-style="{ color: isCredit == 0 ? '' : '#FF8A52' }"
            @click="openCoupon2"
          ></u-cell-item>
        </u-cell-group>
      </template>
    </mescroll-body>
    <!-- 机构的卡卷 -->
    <u-popup
      v-model="couponPopup"
      mode="bottom"
      border-radius="14"
      height="70%"
      class="coupon-wrapper"
    >
      <view class="coupon-title">卡券</view>
      <view class="coupon-list">
        <scroll-view scroll-y="true" class="coupon-scroll">
          <view class="item" v-for="(out, listIndex) in couponList" :key="listIndex">
            <view class="title">{{ out.coupon_type_text }}</view>
            <view
              class="ticket u-flex"
              :class="couponBgColorClass[item.coupon_type]"
              v-for="item in out.list"
              :key="item.id"
            >
              <view class="left">
                <view class="top" v-if="item.coupon_type == 1">
                  <text class="big">{{ item.price | formatCurrency }}</text>
                  满{{ parseFloat(item.maxprice) }}减{{ parseFloat(item.price) }}
                </view>
                <view class="top" v-else-if="item.coupon_type == 2">
                  <text class="big">{{ parseFloat(item.discount) }}折</text>
                </view>
                <view class="top" v-else-if="item.coupon_type == 3"
                  ><text class="big">课程卡</text></view
                >
                <view class="type u-line-1" v-if="item.coupon_type == 3"
                  >仅限{{ item.course_title }}使用</view
                >
                <view class="type u-line-1" v-else>仅限{{ item.school_name }}使用</view>
                <view v-if="item.use_etime" class="date u-line-1"
                  >有效期{{ item.use_stime | timeFormat('yyyy.mm.dd') }}至{{
                    item.use_etime | timeFormat('yyyy.mm.dd')
                  }}</view
                >
                <view v-else class="date u-line-1">永久有效</view>
              </view>
              <view class="right u-flex">
                <view
                  class="use active"
                  :round="true"
                  v-if="couponId == item.id"
                  @click="cancelCoupon(item)"
                  >取消使用</view
                >
                <view class="use" :round="true" v-else @click="useCoupon(item)">使用</view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <!-- 积分弹窗 -->
    <u-popup v-model="couponPopup2" mode="bottom" border-radius="34" height="723">
      <view class="coin">
        <view class="coin-title">积分抵扣</view>
        <scroll-view scroll-y="true" class="scrollY" style="height: 500rpx; width: 100%">
          <u-radio-group v-model="paywayRadio" size="44" style="width: 100%">
            <view class="radio-item" v-for="(item, index) in credit_arr" :key="index">
              <view class="radio_li">
                <view class="left-ltem addClass" v-if="index == 0"
                  >可使用积分 {{ item.credit }}</view
                >
                <view class="left-ltem" v-else>{{ item.credit }}积分</view>
                <view class="right-item" @click="change(item, item.num, index)">
                  <view class="can-num">可抵￥{{ item.num }}</view>
                  <u-radio :name="index" :active-color="globPrimaryColor"></u-radio>
                </view>
              </view>
            </view>
          </u-radio-group>
        </scroll-view>
        <view class="sure" @click="sureClick()">确定</view>
      </view>
    </u-popup>

    <view class="bottom-placeholder">
      <view justify="between" class="u-flex bottom-navbar">
        <view>优惠：{{ sumDiscount | formatCurrency }}</view>
        <view class="right u-flex">
          <view class="total">
            合计：
            <text class="num">{{ sumPrice | formatCurrency }}</text>
          </view>
          <view class="btn" @click="submit">提交订单</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import courseImage from '@/components/common/courseImage.vue'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'
import { mapGetters } from 'vuex'
export default {
  mixins: [MescrollMixin],
  components: {
    courseImage,
  },
  data() {
    return {
      typeClass: { 1: 'video', 2: 'live', 3: 'multipart', 4: 'classes' },
      couponBgColorClass: { 1: 'youhui', 2: 'dazhe', 3: 'kechengka' },
      orderData: {},
      isCoupon: 0,
      isCredit: 1,
      credit_num: 0,
      couponDiscountText: '',
      couponId: 0,
      ticket_id: 0,
      couponPopup: false,
      couponPopup2: false,
      couponList: [],
      sumDiscount: 0,
      sumPrice: 0,
      usePrice: 0, // 储存一个原价
      options: {},
      promotion_id: 0,

      paywayRadio: 0,

      credit_arr: [],
      save_credit: [],
      credit_redeem: 0,
      credit_redeem_percent: 1,
      str_credit: '{}',

      save_item: {},
      save_index: '',
      new_name: 0,
      isSure: 0,
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
    }),
    text() {
      if (this.isCoupon == 0) {
        return '无卡券可使用'
      } else if (this.isCoupon == 1) {
        return '未使用优惠券'
      } else if (this.isCoupon == 2) {
        return this.couponDiscountText
      }
    },
    text2() {
      if (this.isCredit == 0) {
        return `可抵扣￥${this.credit_num}`
      } else {
        return `可抵扣￥${this.credit_num}`
      }
    },
    mescrollHeight() {
      let height = 0
      uni.getSystemInfo({
        success(res) {
          height = res.windowHeight - 44 - 50
        },
      })
      return `${height}px`
    },
  },
  filters: {
    fil_credit(val, value1) {
      return val * value1
    },
    handleTime(timeStamp) {
      if (timeStamp > 0) {
        var date = new Date()
        date.setTime(timeStamp * 1000)
        var y = date.getFullYear()
        var m = date.getMonth() + 1
        m = m < 10 ? '0' + m : m
        var d = date.getDate()
        d = d < 10 ? '0' + d : d
        var h = date.getHours()
        h = h < 10 ? '0' + h : h
        var minute = date.getMinutes()
        var second = date.getSeconds()
        minute = minute < 10 ? '0' + minute : minute
        second = second < 10 ? '0' + second : second
        return y + '年' + m + '月' + d + '日'
      } else {
        return ''
      }
    },
  },
  onLoad(option) {
    this.options = option
    if (!this.$u.test.empty(option) && !this.$u.test.empty(option.promotion_id)) {
      this.promotion_id = option.promotion_id
    }
    this.getOrderCourse()
    // 获取卡卷信息
    this.$edu.api
      .getCouponCourseUser({
        course_id: this.options.id,
        group: 1,
      })
      .then((res) => {
        let data = res.data
        // 过滤空
        data = data.filter((item) => {
          return !this.$u.test.empty(item.list)
        })
        if (this.$u.test.empty(data)) {
          this.isCoupon = 0
        } else {
          this.isCoupon = 1
        }
        this.couponList = data
      })
  },
  methods: {
    getOrderCourse() {
      // 获取订单信息
      this.$edu.api
        .getOrderCourse({
          course_id: this.options.id,
          promotion_id: this.promotion_id,
        })
        .then((res) => {
          const { data } = res
          this.orderData = data
          this.credit_redeem_percent = data.credit_redeem_percent
          this.credit_redeem = data.credit_redeem
          this.credit_arr = data.credit_arr
          if (data.credit_arr.length != 0) {
            this.credit_num = data.credit_arr[0].num
            this.str_credit = JSON.stringify(data.credit_arr[0])
          }
          this.credit_arr.map((el, key) => (key == 0 ? (el.isChose = true) : (el.isChose = false)))
          this.save_credit = this.credit_arr
          if (
            !this.$u.test.empty(data.positive_promotion) &&
            data.positive_promotion.running_status == 1
          ) {
            this.sumPrice = (data.positive_promotion.price * 100 - this.credit_num * 100) / 100
            this.usePrice = data.positive_promotion.price
          } else {
            this.sumPrice = (data.user_price * 100 - this.credit_num * 100) / 100
            this.usePrice = data.user_price
          }
          this.mescroll.endSuccess(1, false)
        })
    },
    openCoupon() {
      if (this.isCoupon != 0) {
        this.couponPopup = true
      }
    },
    openCoupon2() {
      this.couponPopup2 = true
      this.paywayRadio = this.save_index
    },
    // 选择积分
    change(item, name, index) {
      if (item.isChose) {
        this.paywayRadio = null
        this.credit_arr.forEach((el) => (el.isChose = false))
        this.isSure = -1
      } else {
        this.paywayRadio = index
        this.credit_arr.forEach((el, key) =>
          index == key ? (el.isChose = true) : (el.isChose = false)
        )
        this.new_name = name
        this.isSure = 1
      }
      this.save_item = item
    },
    sureClick() {
      this.sumPrice = this.usePrice
      if (this.isSure == -1) {
        this.credit_num = 0
        this.sumPrice = (this.sumPrice * 100 - this.sumDiscount * 100) / 100
        this.isCredit = 0
        this.str_credit = '{}'
        this.couponPopup2 = false
        this.save_index = null
      } else if (this.isSure == 1) {
        this.str_credit = JSON.stringify(this.save_item)
        this.isCredit = 1
        this.credit_num = this.new_name
        this.sumPrice = (this.sumPrice * 100 - this.new_name * 100 - this.sumDiscount * 100) / 100
        this.couponPopup2 = false
        this.credit_arr.forEach((el, key) => {
          if (this.save_item.num == el.num) {
            this.save_index = key
          }
        })
      } else {
        this.isSure == 0
      }
      {
        this.couponPopup2 = false
      }
    },
    // 使用卡卷
    useCoupon(item) {
      if (this.$edu.test.isDef(item.ticket_id)) {
        this.ticket_id = item.ticket_id
      } else {
        this.ticket_id = 0
      }

      let query = {
        course_id: this.options.id,
        promotion_id: this.promotion_id,
      }

      if (this.$edu.test.isDef(item.ticket_id)) {
        query = {
          ...query,
          ticket_id: item.id,
        }
      } else {
        query = {
          ...query,
          coupon_id: item.id,
        }
      }
      this.isCoupon = 2
      this.$edu.api.getCoursecredit(query).then((res) => {
        this.credit_arr = res.data
        if (this.credit_arr.length != 0) {
          this.str_credit = JSON.stringify(this.credit_arr[0])
          this.credit_arr.map((el, key) => (key == 0 ? (el.isChose = true) : (el.isChose = false)))
          this.credit_num = res.data[0].num
          this.paywayRadio = 0
        } else {
          this.credit_num = 0
          this.str_credit = '{}'
        }
        this.yhCoupon(item)
      })

      this.couponPopup = false
      setTimeout(() => {
        this.couponId = item.id
      }, 250)
    },
    // 取消使用
    cancelCoupon(out) {
      this.couponId = 0
      this.ticket_id = 0
      this.isCoupon = 1
      this.sumDiscount = 0
      if (this.save_credit.length > 0) {
        this.credit_num = this.save_credit[0].num
      }
      this.paywayRadio = 0
      this.isCredit = 0
      this.sumPrice = this.usePrice - this.credit_num
      this.couponPopup = false
      this.credit_arr = this.save_credit
    },
    yhCoupon(item) {
      let price = this.usePrice
      if (item.coupon_type == 1) {
        this.couponDiscountText = `满${parseFloat(item.maxprice)}减${parseFloat(item.price)}`
        this.sumDiscount = parseFloat(item.price)
        this.sumPrice = (price * 100 - item.price * 100 - this.credit_num * 100) / 100 // 优惠后支付价格
      } else if (item.coupon_type == 2) {
        this.couponDiscountText = `${item.discount}折`
        let count = parseFloat(price - price * (item.discount / 10)).toFixed(2)
        this.sumDiscount = count
        this.sumPrice = (price * 100 - count * 100 - this.credit_num * 100) / 100 // 打折后支付价格
      } else if (item.coupon_type == 3) {
        this.couponDiscountText = '课程卡'
        this.sumDiscount = price
        this.sumPrice = 0
      }
    },
    // 提交订单
    submit() {
      let query = {
        promotion_id: this.promotion_id,
        course_id: this.orderData.id.toString(),
        credit: this.str_credit,
      }
      if (this.ticket_id) {
        query = {
          ...query,
          ticket_id: this.couponId.toString(),
        }
      } else {
        query = {
          ...query,
          coupon_id: this.couponId.toString(),
        }
      }
      this.$edu.api.postOrderCourse(query).then((res) => {
        const { data } = res
        if (data.need_pay == 1) {
          let params = {
            id: this.orderData.id,
            no: res.data.order_no,
            payment: res.data.payment,
            redirect_type: 'course',
          }
          this.$u.route({
            type: 'redirectTo',
            url: 'pages/pay',
            params: params,
          })
        } else if (data.need_pay == 0) {
          this.$u.route({
            type: 'redirectTo',
            url: '/pageCourse/course/details',
            params: {
              id: this.orderData.id,
            },
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.order ::v-deep.order-wrap {
  margin-top: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  .content {
    flex: 1;
    margin-left: 16rpx;
    .title {
      height: 72rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #333333;
      line-height: 36rpx;
      margin-bottom: 10rpx;
    }
    .count {
      font-size: 22rpx;
      font-weight: 400;
      color: $edu-tips-color;
    }
    .price {
      font-size: 24rpx;
      font-weight: 500;
      color: $edu-price-color;
    }
  }
}
.order-coupon {
  margin-top: 22rpx;
}

.coupon-wrapper {
  .coupon-title {
    font-size: 32rpx;
    font-weight: 500;
    color: #303133;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .coupon-scroll {
    height: 100%;
  }
  .coupon-list {
    padding: 0 30rpx;
    height: calc(100% - 120rpx);
    .item {
      & + .item {
        margin-top: 45rpx;
      }
      .title {
        font-size: 28rpx;
        font-weight: 400;
        color: #909399;
      }
    }
    .ticket {
      margin-top: 32rpx;
      background-image: var(--bg-img);
      background-size: 100% 100%;
      background-repeat: no-repeat;
      .left {
        width: 70%;
        padding: 20rpx 25rpx;
        color: var(--main-color);
        .top {
          font-size: 28rpx;
          .big {
            font-size: 40rpx;
            font-weight: 400;
            margin-right: 10rpx;
          }
        }
        .type {
          font-size: 24rpx;
          margin-top: 18rpx;
        }
        .date {
          margin-top: 6rpx;
          font-size: 24rpx;
        }
      }
      .right {
        width: 30%;
        .use {
          margin-left: auto;
          margin-right: auto;
          width: 150rpx;
          height: 68rpx;
          border-radius: 34rpx;
          border-width: 2rpx;
          border-style: solid;
          color: #ffff;
          font-size: 30rpx;
          line-height: 64rpx;
          text-align: center;
          border-color: var(--main-color);
          background-color: var(--main-color);
          &.active {
            color: var(--main-color);
            border-color: transparent;
            background-color: transparent;
          }
        }
      }
      &.youhui {
        --main-color: #ff8a52;
        --bg-img: url('@/pageCourse/static/images/youhuiquan.png');
      }
      &.dazhe {
        --main-color: #ff9431;
        --bg-img: url('@/pageCourse/static/images/dazhe_bg.png');
      }
      &.kechengka {
        --main-color: #67c23a;
        --bg-img: url('@/pageCourse/static/images/kechengka.png');
      }
    }
  }
}

.bottom-placeholder {
  height: 98rpx;
}

.bottom-navbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  height: 98rpx;
  padding: 0 30rpx;
  background: #ffffff;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);
  .right {
    margin-left: auto;
  }
  .total {
    font-size: 26rpx;
    font-weight: 400;
    color: #303133;
    .num {
      font-size: 30rpx;
      font-weight: 500;
      color: #f54030;
    }
  }
  .btn {
    width: 220rpx;
    height: 72rpx;
    @include bg-color();
    border-radius: 39rpx;
    font-size: 32rpx;
    font-weight: 400;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-left: 28rpx;
  }
}

.coin {
  padding: 30rpx 30rpx 10rpx 30rpx;
  .coin-title {
    height: 45rpx;
    line-height: 45rpx;
    text-align: center;
    font-size: 32rpx;
    color: #303133;
    font-weight: bold;
    margin-bottom: 44rpx;
  }
  .sure {
    height: 72rpx;
    width: 640rpx;
    @include bg-color();
    font-size: 32rpx;
    line-height: 72rpx;
    text-align: center;
    margin: 0 auto;
    color: #ffffff;
    border-radius: 36rpx;
  }
  .radio-item {
    height: auto;
    width: 100%;
    margin-bottom: 56rpx;
    .radio_li {
      display: flex;
      justify-content: space-between;
      .left-ltem {
        height: 44rpx;
        line-height: 44rpx;
        font-size: 30rpx;
        color: #303133;
      }
      .right-item {
        height: 44rpx;
        line-height: 44rpx;
        display: flex;
        .can-num {
          font-size: 26rpx;
          color: #909399;
          margin-right: 23rpx;
        }
      }
    }
  }
}
.addClass {
  font-weight: bold;
}
</style>
